package com.coder.algorithm.leetcode

import java.util.*

/**
 * 56. 合并区间
 * @description: https://leetcode-cn.com/problems/merge-intervals/
 */
class l_0056 {

    fun merge(intervals: Array<IntArray>): Array<IntArray> {
        // 排序
        Arrays.sort(intervals) { o1, o2 -> o1[0] - o2[0] }
        val result = mutableListOf<IntArray>()
        var temp = intervals[0]
        for (i in 1 until  intervals.size) {
            if (temp[1] >= intervals[i][0]) {
                temp[1] = temp[1].coerceAtLeast(intervals[i][1])
            } else {
                result.add(temp)
                temp = intervals[i]
            }
        }
        result.add(temp)
        return result.toTypedArray()
    }
}